package project.daggerdemo.utils;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.observables.ConnectableObservable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by lgs on 2018/3/3.
 */

public class HeavyLibraryWrapper {

    private HeavyExternalLibrary heavyExternalLibrary;

    private boolean isInitialized = false;

    ConnectableObservable<HeavyExternalLibrary> initObservable;

    public HeavyLibraryWrapper() {
        initObservable = Observable.create(new ObservableOnSubscribe<HeavyExternalLibrary>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<HeavyExternalLibrary> subscriber) throws Exception {
                heavyExternalLibrary = new HeavyExternalLibrary();
                heavyExternalLibrary.init();
                subscriber.onNext(heavyExternalLibrary);
                subscriber.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .publish();

        initObservable.subscribe(new SimpleObserver<HeavyExternalLibrary>(){
            @Override
            public void onNext(HeavyExternalLibrary heavyExternalLibrary) {
                isInitialized = true;
            }
        });
        initObservable.connect();
    }

    public void callMethod(){
        if(isInitialized){
            heavyExternalLibrary.callMethod();
        }else {
            initObservable.subscribe(new SimpleObserver<HeavyExternalLibrary>(){
                @Override
                public void onNext(HeavyExternalLibrary heavyExternalLibrary) {
                    heavyExternalLibrary.callMethod();
                }
            });
        }
    }
}
